import { message } from 'antd'
import {
  getRoleList,//分页查询角色
  getResourcesTree,//权限树
  addRole,//新增角色
  editRole,//编辑角色
  getRoleInfoById,//根据角色id查询单个角色信息
  deleteRole,//根据ID删除角色
  testDelete
} from '@/services/api';

export default {
  namespace: 'role',
  state: {
    roleObj: {},
    resourcesTree: [],
    resourcesTreeMap: [],
    singleRoleInfo: {}
  },

  effects: {
    * getRoleList({ payload }, { call, put }) {//获取角色列表
      // const { resolve } = payload;
      const { code, msg, data } = yield call(getRoleList, payload);
      // !!resolve && resolve(code);
      // console.log(data)
      if (code === 1 && data) {
        yield put({
          type: 'updateState',
          payload: {
            roleObj: data,
            // roleList:data.list
          },
        });
      } else {
        message.error(msg)
      }
    },
    * getResourcesTree({ payload }, { call, put }) {//获取角色权限树
      const { resolve } = payload;
      const { code, msg, data } = yield call(getResourcesTree, payload);
      !!resolve && resolve({ code, data });
      if (code === 1 && data) {
        yield put({
          type: 'updateState',
          payload: {
            resourcesTree: data,
          },
        });
      } else {
        message.error(msg)
      }
    },
    * addRole({ payload }, { call, put }) {//新增角色
      const { resolve } = payload;
      const { code, msg, data } = yield call(addRole, payload);
      !!resolve && resolve(code);// 通过resolve返回数据，返回的数据将在Promise的then函数中获取到
      if (code === 1) {
        message.success(msg)
      } else {
        message.error(msg)
      }
    },
    * getRoleInfoById({ payload }, { call, put }) {//根据角色id查询单个角色信息
      const { resolve } = payload;
      const { code, msg, data } = yield call(getRoleInfoById, payload);
      !!resolve && resolve({ code, data });// 通过resolve返回数据，返回的数据将在Promise的then函数中获取到
      if (code === 1) {
        yield put({
          type: 'updateState',
          payload: {
            singleRoleInfo: data
          }
        })
        // message.success(msg)
      } else {
        message.error(msg)
      }
    },
    * editRole({ payload }, { call, put }) {//根据角色id查询单个角色信息
      const { resolve } = payload;
      const { code, msg, data } = yield call(editRole, payload);
      !!resolve && resolve(code);// 通过resolve返回数据，返回的数据将在Promise的then函数中获取到
      if (code === 1) {
        message.success(msg)
      } else {
        message.error(msg)
      }
    },
    * deleteRole({ payload }, { call, put }) {//根据角色id查询单个角色信息
      const { resolve } = payload;
      const { code, msg, data } = yield call(deleteRole, payload);
      !!resolve && resolve(code);// 通过resolve返回数据，返回的数据将在Promise的then函数中获取到
      if (code === 1) {
        message.success(msg)
      } else {
        message.error(msg)
      }
    },

  },

  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  },
};
